import React from 'react';
import {toJS} from 'mobx';
import { inject, observer } from 'mobx-react';
import { WeaTableNew } from 'comsMobx';
const WeaTable = WeaTableNew.WeaTable;
import { WeaColorPicker, WeaTab, WeaLeftRightLayout, WeaTableEditable, WeaRightMenu, WeaDialog, WeaTools, WeaErrorPage, WeaLocaleProvider,WeaMoreButton } from 'ecCom';
import { Button,message } from 'antd';
import './follow.less';
const getLabel = WeaLocaleProvider.getLabel;
@observer
class FollowTypeSetting extends React.Component {
    constructor(props) {
        super(props);
        // this.props.followTypeSettingStore.followComponent = this
        this.state = {
            /* ======================= 列配置数据 ======================= */
            visible:false,
            top:"",
            left:'',
            initialDatas : [
            ],
            custom:{
            },
            columns: [],
            willDeleteKeys:'',
            selectedRowKeys: [],
            /* ======================= 校验规则 ======================= */
            validator: {
                rules: {
                    // required 、max:10 为 validatorjs 默认规则
                    showname: 'required',
                },
                errorMessage: {
                    // 自定义对应规则的错误提示信息
                    required: getLabel('385869','此项必填'),
                },
                // customRegister: [
                //     {
                //       name: "same",
                //       rules: (value, requirement, attribute) => {
                //         return /^#[0-9a-fA-F]{3,6}$/.test(value);
                //       },
                //       errorMessage: ":attribute 不符合颜色值格式"
                //     },
                //     {
                //       name: "maxLen50",
                //       rules: (value, requirement, attribute) => {
                //         return value.length < 51;
                //       },
                //       errorMessage: "最大长度50"
                //     }
                // ]
            },
        };
    }
    componentWillMount(){
        this.props.followTypeSettingStore.getAttentionTypeSet(this)
    }
    componentWillReceiveProps(nextProps) {
        // console.log(nextProps)
        
    }
    getMousePos=(event)=> {
        var e = event || window.event;
        //  return {'x':e.screenX,'y':e.screenY-100}
        this.setState({left:e.screenX,top:e.screenY-100})
    }
    componentDidMount(){
        let that = this
        // this.props.followTypeSettingStore.getAttentionTypeSet('com')
        document.querySelector('.clickFollow').addEventListener("click", function(){
            that.getMousePos()
            that.setState({visible:true})
        });
    }
    getFontColor=(value) =>{
        let red = parseInt(value.substring(1,3),16)
        let green = parseInt(value.substring(3,5),16)
        let blue = parseInt(value.substring(5,7),16)
        let res = red*0.299 + green*0.587 + blue*0.114
        if (res>186){
            return "#000000"
        }else{
            return "#ffffff"
        }
    }
    showSettingColor = (id,color) =>{
        const {followTypeSettingStore} = this.props
        const {colorSetting,setFunc,colorValue} = followTypeSettingStore
        setFunc('colorSetting',true)
        setFunc('operateId',id)
        setFunc('colorValue',color)
    }
    willAdd = (datas, addData) => {
        let color = this.color16(datas);
        //去重
        addData = {...addData,colorval: color};
        datas = [...datas.slice(0,datas.length-1), addData];
        this.setState({initialDatas: datas})
        // console.log(jQuery(".ant-modal-content .ant-table-body table ").height());
        // let scrollheight = jQuery(".ant-modal-content .ant-table-body table ").height();
        // $( ".ant-modal-content .ant-table-body table ").animate({ "scrollTop" : scrollheight +"px"});
        // $( ".ant-modal-content .ant-table-body table ").scrollTop(1000)
    }

    //生成随机的颜色且去重
    color16 = (datas) => {
        let flag = true;
        var r = Math.floor(Math.random()*256);
        var g = Math.floor(Math.random()*256);
        var b = Math.floor(Math.random()*256);
        var color = '#'+(Array(6).join(0) + (r.toString(16)+g.toString(16)+b.toString(16))).slice(-6);
        datas.map(item=>{
            if(item.colorval===color){
                flag  = false;
            }
        })
        if(flag === false){
            color =  this.color16(datas)
        }else{
            return color;
        }
    }


    willDelete=(datas, delData)=>{
        this.setState({willDeleteKeys:String(this.state.selectedRowKeys)})
        this.setState({initialDatas:datas})
    }
    onRowSelect = (selectedRowKeys) => {
        this.setState({ selectedRowKeys });
    }
    getFooter=(type)=> {
        const {followTypeSettingStore} = this.props
        const {colorSetting,setFunc} = followTypeSettingStore
        const menu = [
            {
              key: "0",
              icon: <i className="icon-coms-Preservation" />,
              content: getLabel(86,'保存'),
              onClick: () => this.handleSave("manage")
            },
          ];
        let btns = [];
        if(type==="manage"){
            btns.push(
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@3wm4fk@save`} type='primary' onClick={() => this.handleSave("manage")}>{getLabel('30986','保存')}</Button>,
                <WeaMoreButton ecId={`${this && this.props && this.props.ecId || ''}_WeaMoreButton@qwk1y5@more`} datas={menu} collectParams={{ favouritetype: 2, objid: 0, importantlevel: 1, }}/>
            )
        }else{
            btns.push(
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@wki3xd@save`} type='primary' onClick={() => this.handleSave("color")}>{getLabel('30986','保存')}</Button>
            )
        }
        return btns;
    }
    loadData=()=>{
        const {followTypeSettingStore} = this.props
        const {colorSetting,setFunc,flowTypeData} = followTypeSettingStore 
        let customnew = toJS(flowTypeData.columns[1])
        // console.log(flowTypeData)
        flowTypeData.columns[0].width="60%";
        flowTypeData.columns[0].title=getLabel('511463','关注类型名称')
        customnew.title=getLabel('511464','关注类型颜色')
        flowTypeData.columns[0].com[0].viewAttr=3;
        customnew.com[0]['render']= (text, record, index, onEdit) => (
            <div className={'customColor'} style={{background:this.state.initialDatas[index].colorval,color:this.getFontColor(this.state.initialDatas[index].colorval)}}
              onClick={()=>this.showSettingColor(this.state.initialDatas[index].id,this.state.initialDatas[index].colorval)}>
              {this.state.initialDatas[index].colorval}
            </div>
        )
        let  arr = []
        arr.push(flowTypeData.columns[0],customnew)
        this.setState({columns:arr,initialDatas:toJS(flowTypeData.datas)})
    }
    
    handleSave=(type)=>{
        let that = this
        const {followTypeSettingStore} = this.props
        const {colorSetting,setFunc,colorValue,operateId,saveAttentionTypeSet,getAttentionTypeSet,openType} = followTypeSettingStore
        let arr=[]
        this.state.initialDatas.map((val,index)=>{
            arr.push(val.showname)  
        })
        let narr=arr.sort();
        if(type==="manage"){
          let data = JSON.stringify(this.state.initialDatas)
          let result = this.table.doValidate()
          if(result.pass==false){
              return;
          }else{
            for(let i=0;i<arr.length;i++){
                if (narr[i]==narr[i+1]){
                    message.warning(narr[i]+getLabel('511462','该关注类型已存在'));
                    return;
                }
            }
            setFunc('showDialog',false)
            switch(openType){
                case "bqsz"://标签设置按钮打开
                    saveAttentionTypeSet({data,delIds:this.state.willDeleteKeys,src:'saveData'},this.props.refresh)
                    break;
                case "bdsz"://表单中打开
                    saveAttentionTypeSet({data,delIds:this.state.willDeleteKeys,src:'saveData'},this.props.makeSureCallBack);
                    this.timerID=setTimeout(()=>{ 
                        $(".wf_attention_div_btn").on("mouseover mouseout",function(event){
                            const str = $(this).attr('id').substr($(this).attr('id').indexOf('_'))
                            if(event.type == "mouseover"){  
                             jQuery("#attentionSpan"+str).css("display","inline-block")
                            }else if(event.type == "mouseout"){
                             jQuery("#attentionSpan"+str).css("display","none")
                            }
                           })
                     },2000)
                    break;
                default:
                    saveAttentionTypeSet({data,delIds:this.state.willDeleteKeys,src:'saveData'})
            }
          } 
        }else{
          this.state.initialDatas.map((val)=>{
              if(val.id==operateId){
                  val.colorval=colorValue
              }
          })
          let datas = this.state.initialDatas
          this.setState({initialDatas:datas})
          setFunc('colorSetting',false)
        }
    }
    getRowSelection = rowSelection => {
        let data = this.props.followTypeSettingStore.flowTypeData.disabledArray
        const sel = { ...rowSelection };
        sel.getCheckboxProps = (record) => {
            let flag = false
            data.map(val=>{
                if(record.id==val){
                    flag = true
                }
            })
          return { disabled: flag };
        };
        return  sel ;
      }
    onChange = (datas, other) => {
        // console.log('datas, other: ', datas, other);
        this.setState({ initialDatas:datas });
    }
    addBtnClick=(value)=>{
        const {followTypeSettingStore} = this.props
        const {saveAttentionTypeSet,getAttentionTypeSet} = followTypeSettingStore
        saveAttentionTypeSet({showname:value,src:'saveData2'})
    }
    onVisibleChange=()=>{
        this.setState({visible:false})
    }
    getTableProps = () => {
        const {followTypeSettingStore} = this.props
        const {saveAttentionTypeSet,getAttentionTypeSet} = followTypeSettingStore
        return { scroll: { y: 703 }}
      };
    render() {
        const {followTypeSettingStore} = this.props
        const {colorSetting,setFunc,colorValue,showDialog} = followTypeSettingStore
        const menu = [
            {
              key: "0",
              icon: <i className="icon-coms-Preservation" />,
              content: getLabel(86,'保存'),
              onClick: () => this.handleSave("manage")
            },
          ];
        return (
            <div className="clickFollow" style={{height:"100%"}}>
                {/* <Button onClick={()=>{this.setState({visible:true});this.props.followTypeSettingStore.getAttentionTypeSet('com')}}>
                    222</Button>
                <Button onClick={() => { this.loadData();setFunc('showDialog',true)}}>打开</Button>
                <div className="popShow" style={{position:'absolute',top:this.state.top,left:this.state.left}}>
                    <TagTypeSelect
                        button={'测试'} 
                        data={this.props.followTypeSettingStore.tagList} 
                        visible={this.state.visible} 
                        onVisibleChange={this.onVisibleChange} 
                        addBtn={this.addBtnClick}
                        placement={'leftTop'}
                    >
                    </TagTypeSelect>
                </div> */}
                <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@980gxf`}
                    className={'followType'}
                    title={getLabel('503952','关注类型设置')}
                    visible={showDialog}
                    icon={'icon-coms-workflow'}
                    iconBgcolor="#0079DE"
                    closable={true}
                    hasScroll={true}
                    buttons={this.getFooter('manage')}
                    onCancel={() => { setFunc('showDialog',false),this.setState({willDeleteKeys:''}) }}
                    style={{ height: "1200px", width: "800px" }}>
                    <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@v7ealb`} datas={menu} collectParams={{ favouritetype: 2, objid: 0, importantlevel: 1, }} >
                    <WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEditable@0f2raz`}
                        ref={el => { this.table = el }}
                        datas = {this.state.initialDatas}
                        columns={this.state.columns}
                        draggable={true}
                        draggableType= {'icon'}
                        showTitle= {true}
                        showAdd= {true}
                        showDelete= {true}
                        showCopy= {false}
                        showMove= {false}
                        showCollapse= {false}
                        buttonsType= {'inline'}
                        validatePass= {''}
                        addButtonType= {'normal'}
                        pushTitleIntoHeader= {false}
                        showRowSelect= {true}
                        validator={this.state.validator}
                        getRowSelection={this.getRowSelection}
                        tableProps={this.getTableProps()}
                        // addDropDatas={this.getAddDropDatas()}
                        // moveDropDatas={this.getMoveDropDatas()}

                        willAdd={this.willAdd}
                        willDelete={this.willDelete}
                        // willEdit={this.willEdit}
                        // willCopy={this.willCopy}
                        onChange={this.onChange}
                        onRowSelect={this.onRowSelect}
                    ></WeaTableEditable>
                    </WeaRightMenu>
                    </WeaDialog>
                {
                    <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@fc1xop`}
                    className={'colorset'}
                    title={getLabel('511629','关注类型颜色设置')}
                    visible={colorSetting}
                    icon={'icon-coms-workflow'}
                    iconBgcolor="#0079DE"
                    closable={true}
                    hasScroll={true}
                    buttons={this.getFooter('color')}
                    onCancel={() => { setFunc('colorSetting',false)}}
                    style={{ height: "100px", width: "400px" }}
                    >
                        <div className={'color_picker'}>
                            <WeaColorPicker ecId={`${this && this.props && this.props.ecId || ''}_WeaColorPicker@jr5vwe`}   
                            value={colorValue}
                            onChange={(v)=> setFunc('colorValue',v)}
                            />
                        </div>
                       
                    </WeaDialog>
                }
            </div>
        )
    }

}

export default WeaTools.tryCatch(React,
    props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@iqtoof`} msg={props.error ? props.error : getLabel(383324, ' 对不起，该页面异常，请联系管理员 ') + '！'} />,
    { error: "" }
)(FollowTypeSetting);